package com.admin.model;

import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Sys_Function extends MyDB<Sys_Function>{
	public static final Sys_Function dao = new Sys_Function();
	public Sys_Function() {
		tableName = "sys_function";
	}
	
	// 查询所有数据
	public List<Sys_Function> list(String[] params) {
		List<Sys_Function> list = dao.query(params);
		return list;
	}
	
	// 查询指定用户拥有的权限
	public String getFunByUserId(Long userId){
		StringBuffer sb = new StringBuffer();
		StringBuffer sql = new StringBuffer();
		sql.append(" select rf.function_id from sys_role_function rf ");
		sql.append(" inner join sys_roles r on rf.role_id = r.id ");
		sql.append(" inner join sys_user_role ru on r.id = ru.role_id ");
		sql.append(" inner join sys_users u on ru.user_id = u.id ");
		sql.append(" where u.id = "+userId);
		List<RoleFunction> funs = RoleFunction.dao.find(sql.toString());
		for (RoleFunction fun : funs) {
			sb.append(fun.get("function_id")+",");
		}
		if(null != sb && sb.length() > 0){
			return sb.substring(0,sb.length()-1);
		}
		return null;
	}
	
	/**
	 * 递归树
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONArray listToJson(List<Sys_Function> list,List<RoleFunction> roleFuns){
		JSONArray array = new JSONArray();
		for (Sys_Function sysFunction : list) {
			JSONObject json = dao.makeTreeJson(sysFunction,roleFuns);
			List<Sys_Function> childrenList = dao.list(new String[]{"parent = '" +sysFunction.get("id")+ "'"});
			if(null != childrenList && childrenList.size() > 0){
				json.put("children", listToJson(childrenList,roleFuns));
			}
			array.add(json);
		}
		return array;
	}
	
	/**
	 * 组装数据
	 * 
	 * @param sysCourseDic
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject makeTreeJson(Sys_Function sysFunction,List<RoleFunction> roleFuns) {
		JSONObject json = new JSONObject();
		json.put("id", sysFunction.get("id"));
		json.put("pid", sysFunction.get("parent"));
		json.put("name", sysFunction.get("name"));
		json.put("open", true);
		for (RoleFunction roleFun : roleFuns) {
			if(roleFun.get("function_id").equals(sysFunction.get("id"))){
				json.put("checked", true);
			}
		}
		return json;
	}
}
